package com.eascs.afterloancheck.service.Impl;

import java.math.BigDecimal;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.alibaba.dubbo.config.annotation.Reference;
import com.eascs.admin.o2o.badloan.service.O2oBadLoanService;
import com.eascs.admin.o2o.loan.service.O2oLoanapplyService;
import com.eascs.afterloancheck.dao.LoanCheckDao;
import com.eascs.afterloancheck.entity.CheckLoanEntity;
import com.eascs.afterloancheck.form.CheckLoanQueryForm;
import com.eascs.afterloancheck.service.LoanCheckServicce;
import com.eascs.app.dao.PageResult;
import com.eascs.app.log.Logger;
import com.eascs.app.log.LoggerFactory;
import com.eascs.loan.service.O2oLoanService;
import com.eascs.web.sso.User;
import com.eascs.web.sso.UserHolder;
import com.eascs.workflow.common.entity.wf.ProcessTemplate;
import com.eascs.workflow.common.service.wf.WorkFlowService;
import com.eascs.workflow.common.vo.ModelResult;
import com.eascs.workflow.common.vo.WFRequestParam;

@Service
public class LoanCheckServicceImpl implements LoanCheckServicce {
	private Logger logger = LoggerFactory.getLogger(this.getClass());
	@Autowired
	LoanCheckDao loanCheckDao;

	@Autowired
	private O2oBadLoanService service;

	@Autowired
	private O2oLoanapplyService o2oLoanapplyService;

	@Autowired
	O2oLoanService o2oLoanService;

	@Reference
	WorkFlowService workFlowService;

	@Override
	public PageResult<Object[]> queryListPage(CheckLoanQueryForm form) {
		return loanCheckDao.queryListPage(form);
	}

	@Override
	@Transactional(transactionManager = "o2oTransactionManager")
	public ModelResult<Boolean> insertCheckLoanEntity(CheckLoanEntity entity) {
		logger.info("启动定期贷后检查,fn:insertCheckLoanEntity,CheckLoanEntity:[{}]", entity.toString());
		ModelResult<Boolean> modelResult = new ModelResult<>();
		try {
			CheckLoanEntity EntityByBillCode = queryEntityByBillCode(entity.getBillCode());
			logger.info("-----EntityByBillCode:[{}]", EntityByBillCode);
			if (EntityByBillCode != null) {
				ModelResult<Boolean> startUpResult = startUp(entity);
				if (startUpResult.isSuccess() && startUpResult.getModel()) {
					logger.info("-----111entity.getId:[{}]", EntityByBillCode.getId());
					loanCheckDao.processRevisitStart(EntityByBillCode.getId());
					loanCheckDao.updateCreateTime(EntityByBillCode.getId());
					modelResult.setModel(true);
					return modelResult;
				} else {
					logger.info("-----modelResult:mes:[{}],stack:[{}]", modelResult.getModel(),
							modelResult.getDetailStack());
					modelResult.withError("LoanCheckServicceImpl.error startUp()", startUpResult.getErrMsg());
					throw new RuntimeException("流程启动失败" + startUpResult.getErrMsg()); // 回滚事物
				}
			} else {
				CheckLoanEntity model = loanCheckDao.insertCheckLoanEntity(entity);
				if (model != null) {
					ModelResult<Boolean> startUpResult = startUp(entity);
					if (startUpResult.isSuccess() && startUpResult.getModel()) {
						logger.info("-----222entity.getId:[{}]", entity.getId());
						loanCheckDao.processRevisitStart(entity.getId());
						modelResult.setModel(true);
						return modelResult;
					} else {
						logger.info("-----modelResult:mes:[{}],stack:[{}]", modelResult.getModel(),
								modelResult.getDetailStack());
						modelResult.withError("LoanCheckServicceImpl.error startUp()", startUpResult.getErrMsg());
						throw new RuntimeException("流程启动失败" + startUpResult.getErrMsg()); // 回滚事物
					}
				}
			}

		} catch (Exception e) {
			logger.info("LoanCheckServicceImpl.error.insertCheckLoanEntity(),exception:{}", e);
			System.out.println(e);
			throw new RuntimeException("流程启动失败"); // 回滚事物
		}
		return modelResult.withError("insertCheckLoanEntity.error", "流程启动失败!");
	}

	/**
	 * @Title: startUp
	 * @Description: 启动贷后检查
	 * @author
	 * @param entity
	 * @return
	 * @throws @date
	 *             2017年3月16日 上午9:57:17
	 */
	@Override
	public ModelResult<Boolean> startUp(CheckLoanEntity entity) {
		ModelResult<Boolean> result = new ModelResult<Boolean>();
		try {
			WFRequestParam param = new WFRequestParam();
			param.setReferId(entity.getLoanApplyNo());
			param.setReferCode(entity.getBillCode());
			param.setReferUrl("/rafterloancheck/view_flow");
			param.setSystemModule(ProcessTemplate.SYSTEM_MODULE_O2O);
			param.setProcessType(String.valueOf(ProcessTemplate.PROECESS_TYPE_REGULAR_CHECK_LOAN_AFTER));
			param.setProcessVersion("v1");
			User user = UserHolder.getUser();
			param.setAppliedby(user.getNo());
			param.setAppliedbyName(user.getCname());
			param.setOrgNo(entity.getLtd());

			StringBuffer appliedDes = new StringBuffer("借款人:");
			appliedDes.append(o2oLoanapplyService.findLoanUserEntity(entity.getLoanApplyNo(), entity.getLoanId())
					.getUserFullName());
			appliedDes.append("，放款金额:");
			java.text.DecimalFormat df = new java.text.DecimalFormat("0.00"); // 格式化，保留两位小数
			BigDecimal loanAmount = new BigDecimal(0);
			if ("EA".equals(entity.getLoanType()) || "FQ".equals(entity.getLoanType())) {
				loanAmount = service.findDataByBillCode(entity.getBillCode()).getLoanAmount();
			} else {
				loanAmount = o2oLoanService.queryBillCode(entity.getBillCode()).getLoanAmount();
			}
			appliedDes.append(df.format(loanAmount));
			param.setAppliedDes(appliedDes.toString());
			logger.info("启动贷后检查，参数有贷款单号：【{}】，回访编号：【{}】，系统模块：【{}】，流程类型：【{}】，经营平台id：【{}】", entity.getBillCode(),
					entity.getRevisitCode(), ProcessTemplate.SYSTEM_MODULE_O2O, param.getProcessType(),
					entity.getLtd());
			com.eascs.workflow.common.vo.ModelResult<Boolean> modelResult = workFlowService.instance(param);
			if (modelResult.isSuccess() && modelResult.getModel()) {
				// loanCheckDao.processRevisitStart(parameter);
			} else {
				result.setErrMsg(modelResult.getErrMsg());
				logger.error("启动贷后检查申请失败，贷款单号：【{}】，错误信息{}", entity.getBillCode(), modelResult.getErrMsg());
			}
			return modelResult;
		} catch (Exception e) {
			logger.error("启动贷后检查申请失败，贷款单号：【{}】，错误：{}，", entity.getBillCode(), e);
			return result;
		}
	}

	@Override
	public CheckLoanEntity queryEntityById(String parameter) {
		return loanCheckDao.queryEntityById(parameter);
	}

	@Override
	public CheckLoanEntity queryEntityByReferId(String parameter) {
		return loanCheckDao.queryEntityByReferId(parameter);
	}

	@Override
	public ModelResult<Boolean> update(CheckLoanEntity entity) {
		ModelResult<Boolean> modelResult = new ModelResult<>();
		if (entity == null) {
			modelResult.withError("update.error", "LoanCheckServicceImpl update entity is null");
			return modelResult;
		}
		String id = entity.getId();
		if (StringUtils.isBlank(id)) {
			modelResult.withError("update.error", "LoanCheckServicceImpl update id is null");
			return modelResult;
		}
		/** 对象update操作时，防止为传入null数据替换状态、时间等数据 */
		CheckLoanEntity qd = loanCheckDao.queryEntityById(id);
		if (qd == null) {
			modelResult.withError("update.error", "LoanCheckServicceImpl update getEntity is null");
			return modelResult;
		}
		qd.setLoanNumber(entity.getLoanNumber());
		qd.setRevisiterId(entity.getRevisiterId());
		qd.setYearlySale(entity.getYearlySale());
		qd.setStockMoney(entity.getStockMoney());
		qd.setRevisiterName(entity.getRevisiterName());
		qd.setBalancesReceivable(entity.getBalancesReceivable());
		qd.setMonthlySale(entity.getMonthlySale());
		qd.setMonthlyPurchases(entity.getMonthlyPurchases());
		qd.setNewDebt(entity.getNewDebt());
		qd.setRevisitDate(entity.getRevisitDate());
		qd.setRevisitForm(entity.getRevisitForm());
		qd.setIsEnvironmentChanges(entity.getIsEnvironmentChanges());
		qd.setIsPlaceChanges(entity.getIsPlaceChanges());
		qd.setIsStaffChanges(entity.getIsStaffChanges());
		qd.setIsOutTime(entity.getIsOutTime());
		qd.setIsFamilyChange(entity.getIsFamilyChange());
		qd.setCheckDes(entity.getCheckDes());
		boolean result = loanCheckDao.updateEntityById(qd);
		modelResult.withModel(result);
		return modelResult;
	}

	@Override
	public Integer queryLoanNum(String loanId) {
		return loanCheckDao.queryLoanNum(loanId);
	}

	@Override
	public PageResult<Object[]> listCheckLoanEntity(String billCode) {
		return loanCheckDao.listCheckLoanEntity(billCode);
	}

	@Override
	public Boolean isStartFlow(String billCode) {
		return loanCheckDao.isStartFlow(billCode);
	}

	@Override
	public CheckLoanEntity queryEntityByBillCode(String billCode) {
		// TODO Auto-generated method stub
		return loanCheckDao.queryEntityByBillCode(billCode);
	}

	@Override
	public Boolean deleteEntity(CheckLoanEntity entity) {
		// TODO Auto-generated method stub
		return loanCheckDao.deleteEntity(entity);
	}

}
